package com.rwaste.sms.controller;

import com.rwaste.commonutils.Msg;
import com.rwaste.sms.service.SmsService;
import com.rwaste.sms.utils.MateUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Api(tags = "短信验证")
@CrossOrigin
public class SmsController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @PostMapping("/sendMessage/{mobile}")
    public Msg sendSms(@PathVariable  String mobile){
        //查看验证码是否在redis中5分钟有效
        String code = redisTemplate.opsForValue().get(mobile);
        if (!StringUtils.isEmpty(code)){
            return Msg.success("验证码依然有效");
        }
        //借助工具类产生随机数
        code = MateUtils.generateOne();
        //调用发送方法
        boolean result = smsService.sendSms(mobile,code);

        if (result){
            //发送成功将验证码放到数据库中
            redisTemplate.opsForValue().set(mobile, code, 5, TimeUnit.MINUTES);
            return Msg.success("发送成功");
        }
        return Msg.fail("发送失败，请稍后再试");



    }

}
